package com.atguigu.yygh.user.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YYGHException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.util.ConstantPropertiesUtil;
import com.atguigu.yygh.user.util.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/*==========================================
      时 间:   2022-03-12
      讲 师:   刘  辉
      描 述:   尚硅谷教学团队
 ==========================================*/
@Controller
@RequestMapping("/api/userinfo/wx")
public class WeixinController {


    @Autowired
    private ConstantPropertiesUtil constantPropertiesUtil;
    @Autowired
    private UserInfoService userInfoService;


   @GetMapping("getLoginParam")
   @ResponseBody
   public R getWeixinData() throws UnsupportedEncodingException {
       Map<String,Object> map = new HashMap<String,Object>();

       String encode = URLEncoder.encode(constantPropertiesUtil.getRedirectUrl(), "UTF-8");
       map.put("appid",constantPropertiesUtil.getAppId());
       map.put("scope","snsapi_login");
       map.put("redirect_uri",encode);
       map.put("state", System.currentTimeMillis()+"");
       return R.ok().data(map);
   }

   @GetMapping("/callback")
    public String callback(String code,String state) throws Exception {

       StringBuffer stringBuffer=new StringBuffer();
       StringBuffer append = stringBuffer.append("https://api.weixin.qq.com/sns/oauth2/access_token")
               .append("?appid=%s")
               .append("&secret=%s")
               .append("&code=%s")
               .append("&grant_type=%s");

       String url = String.format(append.toString(), constantPropertiesUtil.getAppId(), constantPropertiesUtil.getAppSecret(), code, "authorization_code");

       String result = HttpClientUtils.get(url);
       JSONObject jsonObject = JSONObject.parseObject(result);
       String openid=jsonObject.getString("openid");

       QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<UserInfo>();
       queryWrapper.eq("openid",openid);
       UserInfo userInfo = userInfoService.getOne(queryWrapper);
       if(userInfo== null){//添加数据

           String url2="https://api.weixin.qq.com/sns/userinfo?access_token="+jsonObject.getString("access_token")+"&openid="+openid;
           JSONObject jsonObject1 = JSONObject.parseObject(HttpClientUtils.get(url2));
           String nickname = jsonObject1.getString("nickname");
           userInfo=new UserInfo();
           userInfo.setOpenid(openid);
           //微信昵称
           userInfo.setNickName(nickname);
           userInfo.setStatus(1);
           userInfoService.save(userInfo);
       }
       Integer status = userInfo.getStatus();

       if(status == 0){
           throw new YYGHException(20001,"该用户已被锁定");
       }

       //返回name和token字符串
       Map<String,String> map = new HashMap<>();
       String name = userInfo.getName();
       if(StringUtils.isEmpty(name)) {
           name = userInfo.getNickName();
       }
       if(StringUtils.isEmpty(name)) {
           name = userInfo.getPhone();
       }
       map.put("name", name);
       String token = JwtHelper.createToken(userInfo.getId(), name);
       map.put("token", token);

       //:1.如果没有绑定过手机号，往前端页面携带一个openid
       //2.如果已经绑定过手机号，往前端页面不用携带一个openid
       if(StringUtils.isEmpty(userInfo.getPhone())){
           map.put("openid", openid);
       }else{
           map.put("openid", "");
       }
       //跳转到前端页面
       return "redirect:http://localhost:3000/weixin/callback?token="+map.get("token")+ "&openid="+map.get("openid")+"&name="+URLEncoder.encode(map.get("name"),"utf-8");
    }
}
